<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>

<!DOCTYPE HTML PUBLIC>
<html>
<head>
<base href="<%=basePath%>">

<title>聊天室</title>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript">
	var socket = null;
	$(function() {
		function parseObj(strData) { //转换对象
			return (new Function("return " + strData))();
		}
		;
		//创建socket对象
		socket = new WebSocket("ws://" + window.location.host +
			"/${pageContext.request.contextPath}/talk/" + $("#userName").val());

		//连接创建后调用
		socket.onopen = function() {
			$("#showMsg").append("连接成功...<br/>");
			getusers();
		};

		function getusers() {
			$.getJSON('chat/info.do', function(data) {
				var talk = document.getElementById("talkId");
				talk.innerHTML = "";
				for (var i = 0; i < data.length; i++) {
					var option2 = document.createElement("option");
					var option = talk.appendChild(option2)
					option.innerHTML = data[i];
					option.valueOf = data[i];

				}
			});
		}

		//接收到服务器消息后调用
		socket.onmessage = function(message) {
			var data = parseObj(message.data);
			if (data.type == "message") {
				$("#showMsg").append("<span style='display:block'>" + getDate() + "</span>");
				$("#showMsg").append("<span style='display:block'>" + data.text + "</span>");
			} else if (data.type == "background") {
				$("#showMsg").append("<span style='display:block'>系统改变背景地址,背景地址是:" + data.text + "</span>");
				$("body").css("background", "url(" + data.text + ")");
			}
			$("#showMsg").scrollTop($("#showMsg")[0].scrollHeight);
		};

		//关闭连接的时候调用
		socket.onclose = function() {
			alert("对方已下线");
		};

		//出错时调用
		socket.onerror = function() {
			alert("出现未知异常，请刷新页面");
		};

		$("#sendButton").click(function() {
			socket.send($("#talkId").val() + "#" + $("#msg").val());
			$("#msg").val("");
		});

		function getDate() {
			var date = new Date();
			var Y = date.getFullYear();
			var M = date.getMonth();
			var D = date.getDate();
			var h = date.getHours();
			var m = date.getMinutes();
			var s = date.getSeconds();
			return Y + "-" + M + "-" + D + " " + h + ":" + m + ":" + s;
		}
		;
	});
</script>
<body>
	<input type="hidden" value="${userName}" id="userName">
	<div id="showMsg"
		style="border: 1px solid; width: 500px; height: 400px; overflow: auto;"></div>
	<div>
		<select id="talkId">
			<option value=""></option>
		</select> <input type="text" id="msg" /> <input type="button" id="sendButton"
			value="发送" />
	</div>
</body>
</html>
